<template>
  <div>
    <div style="padding: 10px 0">
      <el-form ref="form" :inline="true" :model="form">
        <el-form-item
          style="margin-left: 20px"
          label="表名:"
          prop="_tableName_"
          :rules="commonRules(importanceOptions)"
          class="common_Style"
        >
          <myElAutocomplete
            :form="form"
            attributeName="_tableName_"
            :seleteLists="importanceOptions"
            valuekey="Label_Desc"
            @inputEvent="
              (val) =>
                handleBASICstrparam(val, importanceOptions, form, 'tableName')
            "
            placeholder="请选择表名"
          />
        </el-form-item>
        <el-form-item
          label="组件名:"
          prop="componentName"
          :rules="[
            { required: true, message: '请输入组件名', trigger: 'blur' },
          ]"
          label-width="73px"
        >
          <el-input
            v-model.trim="form.componentName"
            clearable
            placeholder="请输入组件名"
          />
        </el-form-item>
        <el-form-item
          label="组件英文名:"
          prop="enName"
          :rules="[
            { required: true, message: '请输入组件英文名', trigger: 'blur' },
          ]"
        >
          <el-input
            v-model.trim="form.enName"
            clearable
            placeholder="请输入组件英文名"
            @input="(value) => (form.enName = value.replace(/[^a-zA-Z]/g, ''))"
          />
        </el-form-item>
        <div class="deepClass">
          <el-form-item
            label="sql编写:"
            prop="sql"
            :rules="[
              { required: true, message: '请输入sql编写', trigger: 'blur' },
            ]"
          >
            <el-input
              type="textarea"
              placeholder="请输入sql编写"
              :autosize="{ minRows: 10, maxRows: 20 }"
              v-model="form.sql"
            ></el-input>
          </el-form-item>
        </div>

        <div style="margin-left: 72px">
          <div class="titleClass">
            组件接收参数:
            <el-button type="primary" @click="handleAdd1">添加参数</el-button>
          </div>
          <div class="bigbox" v-show="form.inParams.length">
            <div
              v-for="(item, index) in form.inParams"
              :key="index"
              class="commonClass"
            >
              <el-form-item label="参数类型:" required>
                <el-select v-model="item.type" placeholder="请选择参数类型">
                  <el-option
                    v-for="item in type_Lists"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item
                label="参数名"
                :prop="`inParams.${index}.name`"
                :rules="[
                  { required: true, message: '请输入参数名', trigger: 'blur' },
                ]"
              >
                <el-input
                  v-model.trim="item.name"
                  clearable
                  placeholder="请输入参数名"
                />
              </el-form-item>
              <div>
                <el-form-item
                  label="备注"
                  :prop="`inParams.${index}.desc`"
                  :rules="[
                    { required: true, message: '请输入备注', trigger: 'blur' },
                  ]"
                >
                  <el-input
                    v-model.trim="item.desc"
                    clearable
                    placeholder="请输入备注"
                  />
                </el-form-item>
                <i
                  class="el-icon-remove"
                  style="
                    font-size: 20px;
                    color: #409eff;
                    cursor: pointer;
                    margin-top: 5px;
                  "
                  @click="handleReduce1(index)"
                ></i>
              </div>
            </div>
          </div>
          <el-form-item
            label="查询返回类型:"
            style="margin-top: 10px"
            prop="return_Type"
            :rules="commonRules(returnTypeLists)"
          >
            <myElAutocomplete
              :form="form"
              attributeName="return_Type"
              :seleteLists="returnTypeLists"
              @inputEvent="handleReturnTypeChange"
              valuekey="Label_Desc"
              width="210px"
              placeholder="请选择返回参数类型"
            />
          </el-form-item>
          <el-form-item
            v-if="form.returnType === 'List'"
            label="集合元素类型："
            prop="element_Type"
            style="margin-top: 10px"
            :rules="commonRules(elementLists)"
          >
            <myElAutocomplete
              :form="form"
              attributeName="element_Type"
              :seleteLists="elementLists"
              @inputEvent="handleReturnElement"
              valuekey="Label_Desc"
              width="210px"
              placeholder="请选择集合元素类型"
            />
          </el-form-item>
        </div>

        <div class="classCenter">
          <el-button class="filter-item" type="primary" @click="handleSave"
            >保存</el-button
          >
          <el-button
            class="filter-item"
            style="margin-left: 10px"
            type="primary"
            v-show="editDate"
            @click="handlecancle(false)"
            >取消</el-button
          >
        </div>
      </el-form>
    </div>
    <objService v-if="$store.state.user.objServicedelog"></objService>
  </div>
</template>

<script>
import {
  projectdatebaseLists,
  projectcustomOperateSelectSql,
  findCanUseVo,
} from "@/api/lowcode";
import objService from "../basiComponents/objService";
import myElAutocomplete from "../commonComponents/myElAutocomplete.vue";
export default {
  name: "customApiSearch",
  components: { objService, myElAutocomplete },
  props: ["editDate"],
  data() {
    return {
      // 筛选框的 form 表单
      form: {
        _tableName_: "",
        return_Type: "",
        element_Type: "",
        tableName: "",
        inParams: [
          // {
          //   type: "String"
          // }
        ],
        returnType: "",
      },
      importanceOptions: [],
      returnTypeLists: [],
      type_Lists: ["String", "int"],
      elementLists: [],
    };
  },
  // async created() {
  //   await this.findAllCanUseVo();
  //   this.form.returnType = this.returnTypeLists[0].value;
  //   // 编辑
  //   if (this.editDate) {
  //     this.form = this.editDate;
  //   }
  // },
  //由于该组件添加了keep-alive缓存，所以每次进入这个组件调用activated生命周期
  async activated() {
    await this.findAllCanUseVo();
    // 编辑
    if (this.editDate) {
      this.form = this.editDate;
      //反显表名
      const obj1 = this.importanceOptions.find(
        (item) => item.value === this.form.tableName
      );
      if (obj1) {
        this.$set(this.form, "_tableName_", obj1.Label_Desc);
      } else {
        this.$set(this.form, "_tableName_", this.form.tableName);
      }
      //反显表名

      //查询返回类型
      const obj2 = this.returnTypeLists.find(
        (item) => item.value === this.form.returnType
      );
      if (obj2) {
        this.$set(this.form, "return_Type", obj2.Label_Desc);
      } else {
        this.$set(this.form, "return_Type", this.form.returnType);
      }
      //查询返回类型

      //集合元素类型
      const obj3 = this.elementLists.find(
        (item) => item.value === this.form.elementType
      );
      if (obj3) {
        this.$set(this.form, "element_Type", obj3.Label_Desc);
      } else {
        this.$set(this.form, "element_Type", this.form.elementType);
      }
      //集合元素类型
    } else {
      this.form.returnType = this.returnTypeLists[0].value;
      this.form.return_Type = this.returnTypeLists[0].Label_Desc;
    }
  },
  methods: {
    handleReturnTypeChange(value) {
      if (value === "+") {
        this.$store.state.user.objServicedelog = true;
        this.form.return_Type = "";
        this.form.returnType = "";
      } else {
        const obj = this.returnTypeLists.find(
          (item) => item.Label_Desc === value
        );
        if (obj) {
          this.form.returnType = obj.value;
        } else {
          this.form.returnType = value;
        }
        if (value === "List | 集合列表") {
          this.$set(
            this.form,
            "element_Type",
            this.elementLists[0]?.Label_Desc ?? ""
          );
          this.$set(
            this.form,
            "elementType",
            this.elementLists[0]?.value ?? ""
          );
        } else {
          this.$set(this.form, "element_Type", "");
          this.$set(this.form, "elementType", "");
        }
      }
    },
    handleReturnElement(value) {
      if (value === "+") {
        this.$store.state.user.objServicedelog = true;
        this.form.element_Type = "";
        this.form.elementType = "";
      } else {
        const obj = this.elementLists.find((item) => item.Label_Desc === value);
        if (obj) {
          this.form.elementType = obj.value;
        } else {
          this.form.elementType = value;
        }
      }
    },
    handleBASICstrparam(val, lists, item, param) {
      const obj = lists.find((v) => v.Label_Desc === val);
      if (obj) {
        item[param] = obj.value;
      } else {
        item[param] = val;
      }
    },
    returnChange(value) {
      if (value === "+") {
        this.$store.state.user.objServicedelog = true;
      }
    },
    async findAllCanUseVo() {
      let res = await findCanUseVo(+sessionStorage.getItem("developLowCodeId"));
      if (res?.code === 200) {
        const lists = res.data.map((item) => {
          return {
            value: item.className,
            label: item.classDesc
              ? `${item.className} | ${item.classDesc}`
              : item.className,
            Label_Desc: item.classDesc
              ? `${item.className} | ${item.classDesc}`
              : item.className,
          };
        });
        this.returnTypeLists = [
          {
            value: "String",
            label: "String | 字符串",
            Label_Desc: "String | 字符串",
          },
          {
            value: "String[]",
            label: "String[] | 字符串数组",
            Label_Desc: "String[] | 字符串数组",
          },
          {
            value: "int",
            label: "int | 整数",
            Label_Desc: "int | 整数",
          },
          {
            value: "int[]",
            label: "int[] | 整数数组",
            Label_Desc: "int[] | 整数数组",
          },
          {
            value: "List",
            label: "List | 集合列表",
            Label_Desc: "List | 集合列表",
          },
          {
            value: "Map",
            label: "Map | 键值对集合",
            Label_Desc: "Map | 键值对集合",
          },
          {
            value: "long",
            label: "long | 长整型",
            Label_Desc: "long | 长整型",
          },
          {
            value: "double",
            label: "double | 双精度浮点数",
            Label_Desc: "double | 双精度浮点数",
          },
          {
            value: "float",
            label: "float | 浮点数",
            Label_Desc: "float | 浮点数",
          },
          {
            value: "List<Map<String,Object>>",
            label: "List<Map<String,Object>>",
            Label_Desc: "List<Map<String,Object>>",
          },
          ...lists,
          {
            value: "+",
            label: "+",
            Label_Desc: "+",
          },
        ];
        const parmesLists = [
          {
            value: "String",
            label: "String | 字符串",
            Label_Desc: "String | 字符串",
          },
          {
            value: "Boolean",
            label: "Boolean | 布尔",
            Label_Desc: "Boolean | 布尔",
          },
          {
            value: "Integer",
            label: "Integer | 整数",
            Label_Desc: "Integer | 整数",
          },
          ...lists,
        ];
        await this.projectdatebaseLists(parmesLists);
      }
    },
    handleAdd1() {
      this.form.inParams.push({
        type: "String",
      });
    },
    handleReduce1(index) {
      this.form.inParams.splice(index, 1);
    },
    async projectdatebaseLists(parmesLists) {
      this.importanceOptions = [];
      this.elementLists = [];
      const res = await projectdatebaseLists(
        +sessionStorage.getItem("developLowCodeId")
      );
      if (res?.code === 200) {
        this.importanceOptions = res.data.map((item) => ({
          value: item.className,
          Label_Desc: item.classDesc
            ? `${item.className} | ${item.classDesc}`
            : item.className,
        }));
        this.elementLists = [
          ...parmesLists,
          ...this.importanceOptions,
          {
            value: "+",
            label: "+",
            Label_Desc: "+",
          },
        ];
      }
    },
    handlecancle(flag) {
      if (this.editDate) {
        this.$emit("close", flag);
      } else {
        this.$parent.$parent.$parent.handledTableBtnSave(
          "数据库sql组件",
          "数据库操作组件列表",
          "customComponents"
        );
      }
    },
    handleSave() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          const parmes = JSON.parse(JSON.stringify(this.form));
          if (parmes.returnType === "List") {
            parmes.returnType = `${parmes.returnType}<${parmes.elementType}>`;
          }
          const res = await projectcustomOperateSelectSql({
            ...parmes,
            projectId: +sessionStorage.getItem("developLowCodeId"),
          });
          if (res?.code === 200) {
            this.$message({
              message: "操作成功",
              type: "success",
            });
            this.handlecancle(true);
          }
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "~@/styles/layout-table.scss";
$rowLength: 2;
@media all and (min-width: 1659px) {
  $rowLength: 2;
  @include calculation($rowLength: $rowLength);
}
@media all and (max-width: 1659px) {
  $rowLength: 3;
  @include calculation($rowLength: $rowLength);
}
.titleClass {
  margin-bottom: 10px;
  color: #5a5e66;
  font-weight: 700;
}
.bigbox {
  border: 1px solid #ccc;
  padding-top: 15px;
  width: 96%;
}
.classCenter {
  display: flex;
  justify-content: center;
}
.commonClass {
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
}
.deepClass ::v-deep .el-form-item {
  width: 98%;
}
.deepClass ::v-deep .el-form-item .el-form-item__content {
  width: 92%;
}
</style>
